﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Web.Ajax.Data.HttpDatabase
{
	public class Path
	{
		public string RequestPath;
		public ContentType ContentType;
		public bool IsCollection;
		public bool IsResource;
		public string PhysicalPath;
		public string CollectionPath;
		public string CollectionPhysicalPath;

		private string[] parts;

		public Path(string p)
		{
			RequestPath = p;
			if(p!=null)
			{
				p=p.Replace("/","\\");
				var parts = p.Split('\\');
			}
		}

		private bool pathAnalyzed = false;
		public void AnalyzePath(ContentType c, bool EnsureCollectionPath)
		{
			if (pathAnalyzed)
				return;
			ContentType = c;
			PhysicalPath = FileSystem.GetPhysicalPath(RequestPath, ContentType.Extension);
			if (File.Exists(PhysicalPath))
			{
				IsResource = true;
				CollectionPath = "";
				for(var i=0;i<parts.Length;i++)
				{
					if(i>0)
						CollectionPath+="\\";
					CollectionPath+=parts[i];
				}
			}
			else
			{
				if (EnsureCollectionPath && !Directory.Exists(PhysicalPath))
					Directory.CreateDirectory(PhysicalPath);
				if (Directory.Exists(PhysicalPath))
				{
					IsCollection = true;
					CollectionPath = RequestPath;
				}
			}
			CollectionPhysicalPath = FileSystem.GetPhysicalPath(CollectionPath);
			pathAnalyzed = true;
		}
	}
}
